<template>
  <view class="container">
    <view class="top">
      <view class="type">
        <view class="title">类别：</view>
        <uni-data-checkbox
          mode="tag"
          v-model="recommendParams.type"
          :localdata="type"
          selectedColor="#ffa500"
          selectedTextColor="#fff"
        ></uni-data-checkbox>
      </view>
      <view class="name">
        <view class="title">名称：</view>
        <uni-easyinput
          v-model="recommendParams.name"
          placeholder="请输入名称"
          :maxlength="-1"
        ></uni-easyinput>
      </view>
      <view class="introduction">
        <view class="title">介绍：</view>
        <uni-easyinput
          type="textarea"
          autoHeight
          v-model="recommendParams.introduction"
          placeholder="请输入介绍 "
          :maxlength="-1"
        ></uni-easyinput>
      </view>
      <view class="price">
        <view class="title">人均价格：</view>
        <uni-easyinput
          v-model="recommendParams.price"
          placeholder="请输入价格"
          type="number"
          :maxlength="-1"
        ></uni-easyinput>
      </view>
      <view class="address">
        <view class="title">地址：</view>
        <uni-easyinput
          v-model="recommendParams.location"
          placeholder="请输入地址"
          type="textarea"
          :maxlength="-1"
        ></uni-easyinput>
        <button @tap="opneMap">
          地图<uni-icons type="location-filled" color="#fff" size="20" />
        </button>
        <uni-popup ref="mapPopup" type="bottom" @change="mapPopupChange">
          <map
            id="map"
            class="mapPopup"
            enable-satellite
            :longitude="mapCenter.longitude"
            :latitude="mapCenter.latitude"
            :scale="mapCenter.scale"
            show-location
            @tap="mapClick"
          >
          </map>
        </uni-popup>
      </view>
      <view class="phone">
        <view class="title">联系电话：</view>
        <uni-easyinput
          v-model="recommendParams.phone"
          placeholder="请输入联系电话"
          type="number"
          :maxlength="11"
        ></uni-easyinput>
      </view>
      <view class="rate">
        <view class="title">评分：</view>
        <uni-rate v-model="recommendParams.rate" allowHalf /><view
          class="rateNum"
        >
          {{ recommendParams.rate }}分</view
        ></view
      >
      <view class="media">
        <uni-file-picker
          limit="9"
          title="最多选择9张图片"
          @select="select"
        ></uni-file-picker>
      </view>
    </view>
    <view class="bottom">
      <view class="cancel" @tap="cancel">取消</view>
      <view class="pubintroduction" @tap="pubRecommend">确定</view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
// @ts-ignore
import qqmapsdk from "@/utils/qqmap-wx-jssdk.js";
import { recommendDataAPI } from "@/services/index";
import mapUtils from "@/utils/map";
import map from "@/utils/map";
const type = ref([
  {
    value: 0,
    text: "美食餐厅",
  },
  {
    value: 1,
    text: "旅游景点",
  },
]);

let mapCenter = ref({
  latitude: 23,
  longitude: 112,
  scale: 12,
});

const getLocation = () => {
  uni.getLocation({
    type: "gcj02",
    success: (res) => {
      mapCenter.value.latitude = res.latitude;
      mapCenter.value.longitude = res.longitude;
      console.log(mapCenter.value);
    },
    fail: (fail) => {
      console.log(fail);
      uni.showToast({
        title: "获取位置失败",
        icon: "error" || "fail",
      });
    },
  });
};

onShow(() => {
  // uni.showToast({
  //   title: "功能正在开发中",
  //   icon: "error" || "fail",
  // });
  // setTimeout(() => {
  //   uni.navigateBack();
  // }, 100);
  getLocation();
});
const recommendParams = ref({
  name: "",
  price: 0,
  introduction: "",
  type: 0,
  rate: 0,
  phone: "",
  is_online: 0,
  location: "",
  longitude: 0,
  latitude: 0,
  images: <any>[],
});
let mapContext = ref();
const mapClick = (e: any) => {
  mapContext.value.removeMarkers({ markerIds: [114514] });
  mapContext.value.addMarkers({
    markers: [
      {
        id: 114514,
        latitude: e.detail.latitude,
        longitude: e.detail.longitude,
        width: 20,
        height: 30,
      },
    ],
  });
  mapContext.value.moveToLocation({
    latitude: e.detail.latitude,
    longitude: e.detail.longitude,
  });
  recommendParams.value.longitude = e.detail.longitude;
  recommendParams.value.latitude = e.detail.latitude;
};
let mapPopup = ref();
let image = {
  type: "",
  is_cover: 1,
  uid: "",
  name: "",
  path: "",
  imgUrl: "",
  is_show: 0,
};
const select = (e: any) => {
  const file = e.tempFiles[0].file;
  image.type = file.fileType;
  image.name = file.name;
  image.uid = file.uuid;
  // 调用 uni.uploadFile 方法上传文件
  uni.uploadFile({
    url: "https://nodes.kimhiz.asia/api/upload",
    filePath: file.tempFilePath,
    name: "file", // 这是后端用来解析文件流的字段名
    header: { type: recommendParams.value.type == 0 ? "food" : "travel" },
    success: (res: any) => {
      // 请求成功，处理服务器响应
      const data = JSON.parse(res.data);
      if (data.code == 200) {
        // 如果服务器返回成功，更新预览图片的URL
        let img = data.data[0].replace(/\\/g, "/");
        image.imgUrl = img;
        image.path = img.split("/")[6]; // 使用 "/" 分割字符串
        recommendParams.value.images.push(image);
      } else {
        // 服务器返回错误信息
        console.error("上传失败:", data.message);
      }
    },
    fail: (err) => {
      // 请求失败，打印错误信息
      console.error("请求失败:", err);
    },
  });
};

const pubRecommend = () => {
  uni.showModal({
    title: "提示",
    content: "是否推荐本数据？",
    showCancel: true,
    success: async (result) => {
      if (result.confirm) {
        if (
          recommendParams.value.name &&
          recommendParams.value.rate &&
          recommendParams.value.phone &&
          recommendParams.value.introduction &&
          recommendParams.value.price &&
          recommendParams.value.location
        ) {
          const { longitude, latitude } = mapUtils.qqMapToBMap(
            recommendParams.value.longitude + "",
            recommendParams.value.latitude + ""
          );
          recommendParams.value.longitude = +longitude;
          recommendParams.value.latitude = +latitude;
          let result: any = await recommendDataAPI(recommendParams.value);
          if (result.code == 200) {
            uni.showToast({
              title: "发表成功",
              icon: "none",
            });
            uni.navigateBack({
              delta: 1,
            });
          } else {
            console.log(result);
          }
        } else {
          uni.showToast({
            title: "请填写完整",
            icon: "none",
          });
        }
      }
    },
    fail: () => {},
    complete: () => {},
  });
};

const opneMap = () => {
  mapPopup.value.open();
  mapContext.value = uni.createMapContext("map");
};
const getCity = () => {
  const QQMapWX = new qqmapsdk({
    //腾讯地图  需要用户自己去申请key
    key: "OAUBZ-RXZKC-RXQ2A-AZJZN-77YLO-UKBGS",
  });

  QQMapWX.reverseGeocoder({
    location: {
      latitude: recommendParams.value.latitude,
      longitude: recommendParams.value.longitude,
    },
    success: function (res: any) {
      recommendParams.value.location =
        res.result.formatted_addresses.standard_address;
    },
  });
};

const mapPopupChange = (e: any) => {
  if (!e.show) {
    getCity();
  }
};

const cancel = () => {
  uni.navigateBack({
    delta: 1,
  });
};
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
  .top {
    border-radius: 15rpx;
    padding: 20rpx;
    background-color: white;
    font-size: 26rpx;
    color: #555;
    .type,
    .name,
    .introduction,
    .price,
    .address,
    .phone,
    .rate {
      display: flex;
      padding: 10rpx 0;
      .title {
        width: 130rpx;
      }
    }
    .address {
      button {
        width: 100rpx;
        height: 65rpx;
        background-color: #ffa500;
        color: #fff;
        border-radius: 15rpx;
        font-size: 20rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 10rpx;
        margin-left: 10rpx;
      }
      .mapPopup {
        height: 80vh;
        width: 100%;
        border-radius: 20rpx 20rpx 0 0;
        overflow: hidden;
        position: relative;

        .mapIcon {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          animation: mapiconJump 0.5s infinite;
        }
        @keyframes mapiconJump {
          0% {
            transform: translate(-50%, -50%);
          }
          50% {
            transform: translate(-50%, -30%);
          }
          100% {
            transform: translate(-50%, -50%);
          }
        }
      }
    }
    .rate {
      .rateNum {
        margin-left: 10rpx;
      }
    }
  }
  .bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    .cancel,
    .pubintroduction {
      width: 49%;
      height: 80rpx;
      border-radius: 15rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #fff;
    }
    .pubintroduction {
      background-color: #ffa500;
      color: #fff;
    }
  }
}
</style>
